<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="shopName" placeholder="请输入店铺名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="platFormOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParam" size="small" :inline="true">
          <el-form-item prop="commodityStatus">
            <el-select v-model="queryParam.commodityStatus" filterable placeholder="商品状态">
              <el-option v-for="item in options" :key="item.commodityStatus" :label="item.label"
                :value="item.commodityStatus">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="pairingStatus">
            <el-select v-model="queryParam.pairingStatus" filterable placeholder="配对状态">
              <el-option v-for="item in options" :key="item.pairingStatus" :label="item.label"
                :value="item.pairingStatus">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="head">
            <el-select v-model="queryParam.head" filterable placeholder="负责人">
              <el-option v-for="item in options" :key="item.head" :label="item.label" :value="item.head">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="select">
            <el-input placeholder="请输入内容" v-model="itemParam.input" class="input-with-select">
              <el-select v-model="itemParam.select" slot="prepend" placeholder="请选择">
                <!-- <el-option label="MSKU" :value="1"></el-option> -->
                <el-option label="FNSKU" :value="1"></el-option>
                <el-option label="ASIN" :value="2"></el-option>
                <el-option label="Seller Sku" :value="6"></el-option>
                <el-option label="sku" :value="3"></el-option>
                <el-option label="gtin" :value="4"></el-option>
                <el-option label="商品名称" :value="5"></el-option>
              </el-select>
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button :disabled="single" @click="handleAddTbProcuredProduct">配对</el-button>
          </el-col>
          <el-col :span="1.5">
            <!-- 分配销售负责人按钮 -->
            <el-button :disabled="multiple" @click="handleAssignSale"
              v-hasPermi="['commodity:relatedProducts:addSaleUser']">分配销售负责人</el-button>

            <!-- 分配产品负责人按钮
            <el-button :disabled="multiple" @click="handleAssignProduct"
              v-hasPermi="['commodity:relatedProducts:addProductUser']">分配产品负责人</el-button> -->
          </el-col>

          <el-col :span="1.5">
            <!-- Dropdown 组件 -->
            <el-dropdown @command="recordingCommand" @visible-change="recordingChange">
              <!-- 触发按钮 -->
              <el-button>
                操作记录
                <!-- 根据 isDropdownVisible 的值动态切换图标方向 -->
                <i :class="isRecordsOperations
                  ? 'el-icon-arrow-up'
                  : 'el-icon-arrow-down'
                  "></i>
              </el-button>

              <!-- 下拉菜单 -->
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="action2">查看配对记录</el-dropdown-item>
                <el-dropdown-item command="action4">查看分配负责人记录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
          <el-col :span="1.5">
            <!-- Dropdown 组件 -->
            <el-dropdown @command="syncCommand" @visible-change="syncChange">
              <!-- 触发按钮 -->
              <el-button>
                同步
                <!-- 根据 isDropdownVisible 的值动态切换图标方向 -->
                <i :class="isSync ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
              </el-button>

              <!-- 下拉菜单 -->
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="action2">更新商品信息</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" height="680px">
          <el-table-column type="selection" width="55" align="center" fixed />
          <el-table-column label="图片" align="center" prop="imageUrl" width="100" fixed>
            <template slot-scope="scope">
              <image-preview v-if="scope.row.imageUrl" :src="scope.row.imageUrl" :width="50" :height="50" />
              <i v-else class="no-image-icon">无图片</i>
            </template>
          </el-table-column>
          <el-table-column label="Seller SKU" prop="sku" align="center" width="150px" />
          <el-table-column label="GTIN" prop="gtin" align="center" width="150px" />
          <el-table-column label="状态" prop="publishedStatus" align="center" width="150px">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.walmart_items_status" :value="scope.row.publishedStatus" />
            </template>
          </el-table-column>
          <el-table-column label="UPC" prop="upc" align="center" width="150px" />
          <el-table-column label="品牌" prop="brandName" align="center" width="180px" />
          <el-table-column label="商品名称" prop="name" align="center" width="180px" />
          <el-table-column label="SKU" prop="productSKU" align="center" width="150px" />
          <el-table-column label="店铺" prop="shopName" align="center" width="150px" />
          <el-table-column label="国家" prop="site" align="center" />
          <el-table-column label="价格" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.currency === 'USD'">$</span>
              <span>{{ scope.row.amount }} </span>
            </template>
          </el-table-column>
          <el-table-column label="销售负责人" prop="saleHead" align="center" fixed="right" width="100px" />
          <el-table-column label="产品负责人" prop="head" align="center" fixed="right" width="100px" />
          <el-table-column label="操作" align="center" fixed="right" width="150">
            <template slot-scope="scope">
              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
                <el-button size="mini" type="text" icon="el-icon-d-arrow-right">解绑</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleRelieveProduct" icon="el-icon-goods">解绑产品和负责人</el-dropdown-item>
                  <!-- <el-dropdown-item command="handleRelieveHead" icon="el-icon-s-custom">解绑负责人</el-dropdown-item> -->
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="itemParam.pageNum" :limit.sync="itemParam.pageSize"
          @pagination="getItemsList()" />
      </el-col>
    </el-row>

    <!-- 添加产品 -->
    <el-dialog :title="titleName" :visible.sync="productOpen" width="1300px" append-to-body>
      <el-row :gutter="20">
        <!-- 产品分类 -->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input v-model="productsName" placeholder="请输入产品名称" clearable size="small" prefix-icon="el-icon-search"
              style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree :data="productsOptions" :props="defaultProps" :expand-on-click-node="false"
              :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
              @node-click="handleNodeClickProduct" />
          </div>
        </el-col>
        <!-- 产品信息 -->
        <el-col :span="20" :xs="24">
          <el-form :model="queryParamProduct" ref="queryFormProduct" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="商品名称/SKU" prop="name">
              <el-input v-model="queryParamProduct.name" placeholder="请输入商品名称/SKU" clearable
                @keyup.enter.native="handleQueryProduct" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParamProduct.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in dict.type.sys_job_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryProduct">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQueryProduct">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table v-loading="loadingProduct" :data="productsList" @selection-change="handleSelectionChange"
            height="510px" ref="myTable">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="图片" align="center" prop="imgName" width="100">
              <template slot-scope="scope">
                <image-preview :src="scope.row.imgName" :width="50" :height="50" />
              </template>
            </el-table-column>
            <el-table-column label="名称" align="center" prop="name">
              <template slot-scope="scope">
                <span v-if="scope.row.name">
                  {{ scope.row.name.slice(0, 10) }}
                  <span v-if="scope.row.name.length > 10">...</span>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="Seller Sku" align="center" prop="sku" />
            <el-table-column label="单价(￥)" align="center" prop="price" />
            <el-table-column label="产品介绍" align="center" prop="brandName" />
            <el-table-column label="备注" align="center" prop="desc">
              <template slot-scope="scope">
                <span v-if="scope.row.desc">
                  {{ scope.row.desc.slice(0, 10) }}
                  <span v-if="scope.row.desc.length > 10">...</span>
                </span>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="totalProduct > 0" :total="totalProduct" :page.sync="queryParamProduct.pageNum"
            :limit.sync="queryParamProduct.pageSize" @pagination="getListProduct" />
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormProduct">配 对</el-button>
        <el-button @click="cancelProduct">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配负责人 -->
    <el-dialog :title="titleName" :visible.sync="assignOpen" width="1300px" append-to-body>
      <el-form :model="queryUserParams" ref="queryUserForm" size="small" :inline="true" v-show="showSearch"
        label-width="68px">
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="queryUserParams.userName" placeholder="请输入用户名称" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="queryUserParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="dateRange" style="width: 180px" value-format="yyyy-MM-dd" type="daterange"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="用户编号" align="center" key="userId" prop="userId" />
        <el-table-column label="用户名称" align="center" key="userName" prop="userName" />
        <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" />
        <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" />
        <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormUser">绑 定</el-button>
        <el-button @click="cancelUser">取 消</el-button>
      </div>

      <pagination v-show="totalUser > 0" :total="totalUser" :page.sync="queryUserParams.pageNum"
        :limit.sync="queryUserParams.pageSize" @pagination="getUserList" />
    </el-dialog>
  </div>
</template>

<script>
import { getPlatFormTree } from "@/api/walmart/auth";
import {
  getList,
  getAddPair,
  // getUpadateProductPair,
  getUpadateSalePair,
  getUpdatePairProduct,
  getSelectPair,
  getUpdateProductId,
  getUpdateHead
} from "@/api/walmart/items";
import {
  listProducts,
  productTreeSelect,
  selectProductBrand
} from "@/api/commodity/products";
import { userList } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "RelatedProducts",
  dicts: [
    "walmart_items_status",
    "walmart_lifecycle_status",
    "sys_job_status",
    "sys_normal_disable",
  ],
  components: { Treeselect },
  data() {
    return {
      options: [],
      // 遮罩层
      loading: false,
      loadingProduct: true,
      // 选中数组
      itemsSKU: [],
      SKU: [],
      id: [],
      nickName: [],
      list: [],
      pairId: [],
      pairIds: [],
      head: [],
      saleHead: [],
      queryParam: {
        pageNum: 1,
        pageSize: 50,
        select: 1
      },
      itemParam: {
        pageNum: 1,
        pageSize: 50,
        authId: null,
      },
      // 用于控制图标方向的变量
      isRecordsOperations: false,
      isSync: false,
      platFormOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      shopName: null,
      total: 0,
      totalUser: 0,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //标题
      titleName: "",
      //是否显示
      productOpen: false,
      assignOpen: false,
      //产品名称
      productsName: null,
      // 分类管理树选项
      productsOptions: [],
      // 产品查询参数
      queryParamProduct: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        catesId: null,
        authId: null,
      },
      // 产品管理表格数据
      productsList: [],
      totalProduct: 0,
      // 显示搜索条件
      showSearch: true,
      pairForm: {
        itemSku: "",
        productId: "",
      },
      // 用户数据
      userList: null,
      // 查询参数
      queryUserParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      // 日期范围
      dateRange: [],
      pairIdLong: null,
    };
  },
  created() {
    this.getPlatForm();
    // this.getItemsList();
    this.getProductTree();
    this.getUserList();
  },
  watch: {
    // 根据名称筛选部门树
    shopName(val) {
      this.$refs.tree.filter(val);
    },
    // 根据产品名称筛选部门树
    productsName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.SKU = selection.map((item) => item.sku);
      this.id = selection.map((item) => item.id);
      this.nickName = selection.map((item) => item.nickName);
      this.pairId = selection.map((item) => item.pairId);
      this.head = selection.map((item) => item.head);
      this.saleHead = selection.map((item) => item.saleHead);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 重置 */
    resetQuery() {
      this.itemParam.select = null;
      this.itemParam.input = null;
      this.handleQuery();
    },
    recordingCommand(command) { },
    recordingChange(visible) {
      this.isRecordsOperations = visible;
    },
    syncCommand(command) { },
    syncChange(visible) {
      this.isSync = visible;
    },

    /** 查询店铺名称列表 */
    getPlatForm() {
      getPlatFormTree().then((response) => {
        this.platFormOptions = response.data;
      });
    },
    handleNodeClick(data) {
      this.itemParam.authId = data.value;
      this.queryParamProduct.authId = data.value;
      this.handleQuery();
    },
    handleQuery() {
      // this.itemParam.pageNum = 1;
      this.getItemsList();
    },
    getItemsList() {
      this.loading = false;
      getList(this.itemParam).then((response) => {
        this.list = response.rows;
        this.total = response.total;
      });
    },

    handleAddTbProcuredProduct(row) {
      this.pairIds = row.pairId || this.pairId;
      if (this.pairIds[0] === null) {
        this.titleName = "配对产品";
        this.productOpen = true;
        this.getListProduct();
        this.itemsSKU = row.sku || this.SKU;
      } else {
        getSelectPair(this.pairIds).then((response) => {
          for (let i = 0; i < response.data.length; i++) {
            if (response.data[i] == null) {
              this.titleName = "配对产品";
              this.productOpen = true;
              this.getListProduct();
            } else {
              this.$modal.msgWarning("已是配对数据！");
            }
          }
        });
      }
    },
    /** 查询部门下拉树结构 */
    getProductTree() {
      productTreeSelect().then((response) => {
        this.productsOptions = response.data;
      });
    },
    //产品节点单机事件
    handleNodeClickProduct(data) {
      this.queryParamProduct.catesId = data.id;
      this.handleQueryProduct();
    },
    /** 产品搜索按钮操作 */
    handleQueryProduct() {
      this.queryParamProduct.pageNum = 1;
      this.getListProduct();
    },
    /** 查询产品列表 */
    getListProduct() {
      this.loadingProduct = true;

      selectProductBrand(this.queryParamProduct).then((response) => {
        this.productsList = response.rows;
        this.totalProduct = response.total;
        this.loadingProduct = false;
      });
    },
    resetQueryProduct() {
      this.resetForm("queryFormProduct");
      this.handleQueryProduct();
    },
    /** 取消产品 */
    cancelProduct() {
      this.productOpen = false;
      this.$refs.myTable.clearSelection();
      this.handleQuery();
    },
    submitFormProduct(row) {
      const id = row.id || this.id;
      if (id.length > 1) {
        this.$modal.msgWarning("不允许配对多个商品");
      } else {
        this.pairForm.itemSku = this.itemsSKU[0];
        this.pairForm.pairId = this.pairId[0];
        if (this.pairForm.itemSku != null) {
          this.pairForm.productId = id[0];
          getAddPair(this.pairForm).then((response) => {
            this.$modal.msgSuccess("配对成功");
            this.productOpen = false;
            this.handleQuery();
          });
        } else {
          getUpdateProductId(this.pairIds[0], id[0]).then((response) => {
            this.$modal.msgSuccess("配对成功");
            this.productOpen = false;
            this.handleQuery();
          });
        }
      }
    },
    // handleAssign(row) {
    //   this.pairIds = row.pairId || this.pairId;
    //   const containsNull = this.pairIds.some((element) => element === null);
    //   if (containsNull) {
    //   this.$modal.msgWarning("不允许未配对数据分配负责人！");
    //   } else {
    //   this.head = row.head || this.head;
    //   if (this.head.includes(null)) {
    //     this.titleName = "分配负责人";
    //     this.assignOpen = true;
    //     this.getUserList();
    //   } else {
    //     this.$modal.msgWarning("该数据已经有负责人了！");
    //   }
    //   // }
    // },
    // 处理分配销售负责人
    handleAssignSale(row) {
      this.head = row.head || this.head;
      if (this.head.includes(null)) {
        this.titleName = "分配销售负责人";
        this.flag = false;
        this.assignOpen = true;
        this.getUserList();
      } else {
        this.$modal.msgWarning("该数据已经有销售负责人了！");
      }
    },

    // // 处理分配产品负责人
    // handleAssignProduct(row) {
    //   this.saleHead = row.saleHead || this.saleHead;

    //   if (this.saleHead.includes(null)) {
    //     this.titleName = "分配产品负责人";
    //     this.flag = true;
    //     this.assignOpen = true;
    //     this.getUserList();
    //   } else {
    //     this.$modal.msgWarning("该数据已经有产品负责人了！");
    //   }
    // },
    /** 查询用户列表 */
    getUserList() {
      this.loading = false;
      userList(this.addDateRange(this.queryUserParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          this.totalUser = response.total;
        }
      );
    },
    handleUserQuery() {
      this.queryUserParams.pageNum = 1;
      this.getUserList();
    },
    /** 重置按钮 */
    resetUserQuery() {
      this.dateRange = [];
      this.resetForm("queryUserForm");
      this.queryUserParams.deptId = undefined;
      this.handleUserQuery();
    },

    /** 确定负责人 */
    submitFormUser(row) {
      const head = row.nickName || this.nickName;
      if (head.length > 1) {
        this.$modal.msgWarning("只能选中一个用户！");
      } else {

        // getUpadateProductPair(this.pairIds, head).then((response) => {
        //   this.$modal.msgSuccess("配对成功");
        //   this.assignOpen = false;
        //   this.handleQuery();
        // });

        getUpadateSalePair(this.pairIds, head).then((response) => {
          this.$modal.msgSuccess("配对成功");
          this.assignOpen = false;
          this.handleQuery();
        });
      }
    },
    cancelUser() {
      this.assignOpen = false;
      this.handleQuery();
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleRelieveProduct":
          this.handleRelieveProduct(row);
          break;
        case "handleRelieveHead":
          this.handleRelieveHead(row);
          break;
        default:
          break;
      }
    },
    handleRelieveProduct(row) {
      if (this.SKU.length > 1) {
        this.$modal.msgError("解绑只能选中一个商品！");
        return;
      }
      if (!row.pairId) {
        this.$modal.msgWarning("该商品未匹配，无需解绑！");
        return;
      }
      this.$modal
        .confirm("是否确认解绑该产品和负责人")
        .then(() => {
          // 使用箭头函数确保 this 指向正确
          return getUpdatePairProduct(row.pairId);
        })
        .then(() => {
          this.handleQuery();
          this.$modal.msgSuccess("解绑产品成功！");
        })
        .catch(() => {
          this.$modal.msgError("解绑负责人失败，只能解绑自己的产品或者其他错误！");
        });
    },

    handleRelieveHead(row) {
      if (this.SKU.length > 1) {
        this.$modal.msgError("解绑只能选中一个商品！");
        return;
      }
      if (!row.head) {
        this.$modal.msgWarning("该商品未分配负责人，无需解绑！");
        return;
      }
      this.$modal
        .confirm("是否确认解绑该负责人")
        .then(function () {
          return getUpdateHead(row.pairId);
        })
        .then(() => {
          this.handleQuery();
          this.$modal.msgSuccess("解绑负责人成功！");
        })
        .catch(() => {
          this.$modal.error("解绑负责人失败，只能解绑自己的产品或者其他错误！");
        });
    },
  },
};
</script>

<style>
.el-select .el-input {
  width: 130px;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>
